<!-- eslint-disable @typescript-eslint/no-non-null-assertion -->
<template>
  <div class="org-edit">
    <div class="org-edit-content">
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 600px"
        ref="ruleFormRef"
        :rules="rules"
      >
        <el-form-item label="机构全称" prop="orgName">
          <el-input v-model="form.orgName" />
        </el-form-item>
        <el-form-item label="机构简称" prop="orgNameAlias">
          <el-input v-model="form.orgNameAlias" />
        </el-form-item>
        <el-form-item label="API token">
          <el-input v-model="form.token" />
        </el-form-item>
        <el-form-item label="有效时间" prop="endDate">
          <el-col :span="11">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="开始时间"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="结束时间"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.state" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            :action="config.baseURL + `/api/file/oss/upload`"
            method="post"
            v-model:file-list="form.attachmentUrls"
            list-type="picture-card"
            :limit="5"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            :headers="{ Token: token }"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <div class="org-edit-botton">
          <el-form-item>
            <el-button
              color="rgb(222, 41, 16)"
              type="primary"
              @click="submitForm(ruleFormRef)"
              >保存</el-button
            >
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router"; // 引入useRouter函数
import { Plus } from "@element-plus/icons-vue";
import { config } from "@/request/httpBaseUrl";
import { ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import http from "@/request/request";

const router = useRouter(); // 获取路由实例
const route = useRoute();
//-----------------------------------------------------------变量------------------------------------//
interface SubOrgInfo {
  id?: number; // id
  orgName: string; // 机构名称
}
interface OrgForm {
  id?: number; // id
  orgName: string; // 机构名称
  token: string; // api token
  startDate: string; // 有效时间的开始时间
  endDate: string; // 有效时间的结束时间
  state: boolean; // 状态
  remark: string; // 备注
  attachmentNames?: string[];
  attachmentUrls: UploadUserFile[]; //附件地址
  subOrgIdsAndNames: SubOrgInfo[];
  orgNameAlias: string;
}
// do not use same name with ref
const form = ref<OrgForm>({
  orgName: "",
  token: "",
  startDate: "",
  endDate: "",
  state: true,
  remark: "",
  attachmentUrls: [],
  subOrgIdsAndNames: [],
  orgNameAlias: "",
});
const editOrAdd = ref(true);
const token = ref<string>("");
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<OrgForm>>({
  orgName: [{ required: true, message: "请输入机构全称", trigger: "blur" }],
  orgNameAlias: [
    { required: true, message: "请输入机构简称", trigger: "blur" },
  ],
  endDate: [{ required: true, message: "请输入有效时间", trigger: "blur" }],
});

// --------------------------------------------方法-----------------------------------------------------//
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (editOrAdd.value) {
        addOrgInfo();
      } else {
        updateOrgInfo();
      }
      router.push("/organization");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.back();
};

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
// 删除文件
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  form.value.attachmentNames = uploadFiles.map((f) => f.name);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 文件上传成功
const uploadSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
  uploadFiles
) => {
  console.log(response, uploadFile, uploadFiles);

  if (response.code != 2000) {
    ElMessage.error("上传失败");
  } else {
    form.value.attachmentNames?.push(response.data.url);
  }
};
// 查询机构详细信息
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getOrgInfo = async (id: any) => {
  try {
    const { data } = await http.get<OrgForm>("/api/system/getOrgDetail", {
      orgId: id,
    });
    form.value = data;
    if (form.value.attachmentUrls === null) {
      form.value.attachmentUrls = [];
    }
    form.value.attachmentNames = form.value.attachmentUrls.map((u) => u.name);
  } catch (err) {
    console.log(err);
  }
};
// 更新机构信息
const updateOrgInfo = async () => {
  try {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { attachmentUrls, ...params } = form.value;
    await http.post("/api/system/updateOrganization", params);
  } catch (err) {
    console.log(err);
  }
};
// 添加机构信息
const addOrgInfo = async () => {
  try {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { attachmentUrls, ...params } = form.value;
    await http.post("/api/system/createOrganization", params);
  } catch (err) {
    console.log(err);
  }
};

//-----------------------------生命周期-------------------------------//
onMounted(() => {
  token.value = localStorage.getItem("token") || "";
  const id = route.query.id;
  // 判断是否有参数传递，如果有参数传递，则进行请求接口，视为修改，否则视为添加
  if (id) {
    editOrAdd.value = false;
    getOrgInfo(id);
  }
});
</script>

<style lang="less" scoped>
.org-edit {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  background-color: rgb(255, 255, 255);
  .org-edit-content {
    width: 60%;
    padding: 20px;
    padding-top: 50px;
  }
  .org-edit-botton {
    position: absolute;
    left: 65%;
    top: 85%;
    .el-button {
      width: 160px;
    }
  }
}
</style>